package com.fh.controller.loantask;

import com.fh.annotation.Excel;
import com.fh.annotation.SysLog;
import com.fh.controller.base.BaseController;
import com.fh.mapper.loan.CallLoanInfoMapper;
import com.fh.model.Page;
import com.fh.model.loan.CallLoanInfo;
import com.fh.model.loan.TransferHistoryInfo;
import com.fh.service.loantaskimpl.LoanTaskToBeServiceImpl;
import com.fh.service.system.organization.OrganizationServiceImpl;
import com.fh.util.*;
import com.ybd.common.mask.MaskTypeEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * create by xuxiaorong
 */
@Controller
@RequestMapping("/loanTaskToBe")
public class LoanTaskToBeController extends BaseController {

    @Autowired
    private LoanTaskToBeServiceImpl loanTaskToBeService;

    @Autowired
    private OrganizationServiceImpl organizationService;
    
    @Autowired
	private CallLoanInfoMapper callLoanInfoMapper;


    /***
     * 待催收列表页面 pat test
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("/list2")
    public String list(Page page,Model model) throws Exception {
        //获取页面参数
        PageData pageData =  loanTaskToBeService.setPdWithTrim(this.getPageData());
        
        Map<String, String> map = UserUtils.getCurrentRole();
        Integer QX1 = Integer.valueOf(map.get(Const.SESSION_QX1));
		Integer QX3 = Integer.valueOf(map.get(Const.SESSION_QX3));
		Integer QX4 = Integer.valueOf(map.get(Const.SESSION_QX4));
		Integer QX5 = Integer.valueOf(map.get(Const.SESSION_QX5));
		
		
        
        String sortFind = pageData.getString("sortFindByAmount");
        String sortFindday = pageData.getString("sortFindByDay");
        if(StringUtils.isEmpty(sortFind)&&StringUtils.isEmpty(sortFindday)){
        	pageData.put("sortFind", "create_time DESC,id");
        }else if(!StringUtils.isEmpty(sortFind)&&StringUtils.isEmpty(sortFindday)){
            if(sortFind.equals("0")) {
            	pageData.put("sortFind", "overdue_amount,create_time DESC,id");
            	model.addAttribute("sortFindByamount", 0);
            }
            if(sortFind.equals("1")) {
            	pageData.put("sortFind", "overdue_amount desc,create_time DESC,id");
            	model.addAttribute("sortFindByamount", 1);
            }
        }else if(StringUtils.isEmpty(sortFind)&&!StringUtils.isEmpty(sortFindday)){
            if(sortFindday.equals("0")) {
            	pageData.put("sortFind", "overdue_date,create_time DESC,id");
            	model.addAttribute("sortFindByday", 0);
            }
            if(sortFindday.equals("1")) {
            	pageData.put("sortFind", "overdue_date desc,create_time DESC,id");
            	model.addAttribute("sortFindByday", 1);
            }
        }else{
        	pageData.put("sortFind", "create_time DESC,id");
        }
        //设置数据权限
        page.setPd(UserUtils.setGroupRole(pageData,organizationService));
        R.setPageHelper(pageData);
		List<PageData> toBeList = loanTaskToBeService.getToBeList(page);
		R.setPage(page, toBeList);
		Map<String,MaskTypeEnum> properties = new HashMap<>();
        properties.put(Const.TELE_PHONE,MaskTypeEnum.MOBILE);
        properties.put(Const.CONT_ID_CARD2,MaskTypeEnum.IDCARD2);
        if(toBeList.size() != 0) CoverUtil.setListCover(toBeList,properties);//加密
        model.addAttribute("resultList",toBeList);
        model.addAttribute("page", page);
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        session.setAttribute("page1",page);
        model.addAttribute("pd", page.getPd());
        model.addAttribute(Const.SESSION_QX1,QX1);
        model.addAttribute(Const.SESSION_QX3,QX3);
        model.addAttribute(Const.SESSION_QX4,QX4);
        model.addAttribute(Const.SESSION_QX5,QX5);
        return "loantask/loanTaskToBeList";
    }
	
	/***
	 * version 2.0
	 * 待催收列表页面 pat test
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model) throws Exception {
		Map<String, String> map = UserUtils.getCurrentRole();
		Integer QX1 = Integer.valueOf(map.get(Const.SESSION_QX1));
		Integer QX3 = Integer.valueOf(map.get(Const.SESSION_QX3));
		Integer QX4 = Integer.valueOf(map.get(Const.SESSION_QX4));
		model.addAttribute(Const.SESSION_QX1,QX1);
		model.addAttribute(Const.SESSION_QX3,QX3);
		model.addAttribute(Const.SESSION_QX4,QX4);
		return "loantask/loanTaskToBeListN";
	}
	/***
	 * pageHelper
	 * version 2.1
	 * 待催收列表页面 pat test
	 * @return
	 */
	@RequestMapping("/list/data")
	@ResponseBody
	public Object getDataList2(Page page){
		//获取页面参数
		PageData pageData =  loanTaskToBeService.setPdWithTrim(this.getPageData());
		//要排序的字段
		String sortFiled = pageData.getString("sidx");
		//排序类型
		String sortType = pageData.getString("sord");
		
		if(StringUtils.isEmpty(sortFiled)){
			pageData.put("sortFind", "create_time DESC,id");
		}else if(!Objects.isNull(sortFiled)){
			pageData.put("sortFind", sortFiled + " " + sortType +",create_time DESC,id");
		}else{
			pageData.put("sortFind", "create_time DESC,id");
		}
		//设置数据权限
		page.setPd(UserUtils.setGroupRole(pageData,organizationService));
		
		R.setJqGridPageHelper(pageData);
		List<PageData> toBeList = loanTaskToBeService.getToBeList(page);
		Map<String ,Object> result = R.setJqGridPage(toBeList);
		
		Map<String,MaskTypeEnum> properties = new HashMap<>();
		properties.put(Const.TELE_PHONE,MaskTypeEnum.MOBILE);
		properties.put(Const.CONT_ID_CARD2,MaskTypeEnum.IDCARD2);
		//加密
		if(toBeList.size() != 0) {
			CoverUtil.setListCover(toBeList,properties);
		}
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		session.setAttribute("page1",page);
		return  result;
	}
    
    @RequestMapping("/getSelectVal")
    @ResponseBody
    public List<Map<String,String>> getSelectVal(){
        List<Map<String,String>> mapList = new LinkedList<>();
        Map<String,String> map0 = new HashMap<>();
        map0.put("id"," ");
        map0.put("text","请选择");
        mapList.add(map0);
        Map<String,String> map1 = new HashMap<>();
        map1.put("id","S1");
        map1.put("text","S1");
        mapList.add(map1);
        Map<String,String> map2 = new HashMap<>();
        map2.put("id","S2");
        map2.put("text","S2");
        mapList.add(map2);
        Map<String,String> map3 = new HashMap<>();
        map3.put("id","S2+");
        map3.put("text","S2+");
        mapList.add(map3);
        Map<String,String> map4 = new HashMap<>();
        map4.put("id","M1");
        map4.put("text","M1");
        mapList.add(map4);
        Map<String,String> map5 = new HashMap<>();
        map5.put("id","M2");
        map5.put("text","M2");
        mapList.add(map5);
        Map<String,String> map6 = new HashMap<>();
        map6.put("id","M3");
        map6.put("text","M3");
        mapList.add(map6);
        Map<String,String> map7 = new HashMap<>();
        map7.put("id","M3+");
        map7.put("text","M3+");
        mapList.add(map7);
        return mapList;
    }
	
	/*
	 * 导出信息到EXCEL v2.0
	 * @return
	 */
	@SysLog("任务管理-待催收Excel导出")
	@Excel("逾期客户表-待催收")
	@RequestMapping("/excel2")
	public ModelAndView outExcel(Page page) {
		ModelAndView mv = this.getModelAndView();
		Map<String, Object> dataMap = new HashMap<>();
		try {
			//检索条件===
			//获取页面参数
			PageData pageData = loanTaskToBeService.setPdWithTrim(this.getPageData());
			//设置数据权限
			page.setPd(UserUtils.setGroupRole(pageData, organizationService));
			
			String titles = "催收编号,借款人姓名,借款产品名称,逾期期数,待还金额,逾期阶段,逾期天数,入案时间,还款订单号";
			String fields = "call_loan_nid,real_name,product_name,period,overdue_amount,overdue_stage,overdue_date,create_time,repayment_id";
			List<PageData> userList = loanTaskToBeService.getToBeList2(page);
			
			userList = userList.stream().map(x->{
				Timestamp datetime = (Timestamp) x.get("create_time");
				LocalDateTime date = LocalDateTime.ofInstant(datetime.toInstant(), ZoneId.systemDefault());
				x.put("create_time",date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
				return x;
			}).collect(Collectors.toList());
			
			dataMap = ExportUtil.setExcelData(titles,fields,userList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		mv.addObject(dataMap);
		return mv;
	}
	 
	 /**
	  * 批量委派
	  * @param ids
	  * @return
	  */
	 @SysLog("任务管理-批量委外")
	 @RequestMapping(value="/toWeiwai")
	 @ResponseBody
	 public String outPush(@RequestParam("ids") String[] ids,String flag){
		 String result="";
		 try{
			 Map<String,Object> map=new HashMap<>(16);
			 map.put("ids",ids);
			 //委外流转
			 map.put("transferHistoryInfoList",getTransferHistoryInfolist(ids,flag));
			 int i=loanTaskToBeService.updateByIdWeiwai(map);
			 if(i!=0){
				 result="success";
			 }
		 }catch(Exception e){
			 logger.error("批量委派异常：", e);
		 }
		return result;
	 }
	 
	 //委外流转
	 public List<TransferHistoryInfo>  getTransferHistoryInfolist(String[] fpIds,String flag){
		 List<TransferHistoryInfo> transferHistoryInfolist = new ArrayList<>();
		 for(String callLoanNid:fpIds){
			 TransferHistoryInfo transferHistoryInfo = new TransferHistoryInfo();
			 Map<String,Object> parm = new HashMap<>();
			 //案件编号
			 parm.put("callLoanNid",callLoanNid);
			 CallLoanInfo callLoanInfo = callLoanInfoMapper.findCallLoanInfoSingle(parm);
			 transferHistoryInfo.setCallLoanNid(callLoanNid);
			 transferHistoryInfo.setOverdueStage(callLoanInfo.getOverdueStage());
			 transferHistoryInfo.setStartTime(new Date());
			 transferHistoryInfo.setCurrentStatus(Objects.equals("2",flag) ? 0 :5);
			 transferHistoryInfo.setOperator(UserUtils.getUser().getUSER_ID());
			 transferHistoryInfo.setTransferDesc(
			 		Objects.equals("1",flag) ? "委内催收中案件分派委外公司" :
							(Objects.equals("2",flag) ? "委内催收中案件回收到待催收" : "委内待催收案件分派委外公司")
			 );
			 transferHistoryInfo.setUpdateTime(new Date());
			 transferHistoryInfo.setCreateTime(new Date());
			 transferHistoryInfo.setToCallUid(-1);//当前催收员
	         transferHistoryInfo.setFromCallUid(callLoanInfo.getCallUser()==null ? -1 : callLoanInfo.getCallUser());//之前催收员
			 transferHistoryInfo.setOverdueCaptial(callLoanInfo.getOverdueCaptial());//流转当期逾期本金
             transferHistoryInfo.setOverdueInterest(callLoanInfo.getOverdueInterest());//流转当期逾期利息
             transferHistoryInfo.setOverdueManFee(callLoanInfo.getOverdueManFee());//流转当期逾期管理费
             transferHistoryInfo.setOverdueSerFee(callLoanInfo.getOverdueSerFee());//流转当期逾期服务费
             transferHistoryInfo.setInOverdueFee(callLoanInfo.getOverdueFee());//流转当期逾期罚息
			 transferHistoryInfolist.add(transferHistoryInfo);
		 }
		 return transferHistoryInfolist;
	 }
	 /**
	  * 内催的回到待催收中
	  * @param ids
	  * @return
	  */
	 @RequestMapping(value="/innerCaseBack")
	 @ResponseBody
	 public String innerCaseBack(@RequestParam("ids") String[] ids){
		 String result="";
		 
		 try{
			 Map<String,Object> map=new HashMap<String,Object>();
			 map.put("ids",ids);
			 //委内催收中案件回收到待催收 流转
			 String flag = "2";
			 map.put("transferHistoryInfoList",getTransferHistoryInfolist(ids,flag));
			 int i=loanTaskToBeService.updateInnerBackOne(map);
		 
			 if(i!=0){
				 result="success";
			 }
		 }catch(Exception e){
			 logger.error("案件回收异常：", e);
		 }
		 return result;
	 }
}
